package com.demo.hjh.thread.third;

import java.util.ArrayList;
import java.util.List;

public class Plate2 {  
    /** 装鸡蛋的盘子 */  
	volatile List<Object> eggs = new ArrayList<Object>();  
	
	//Object o1 =  new Object();
	//Object o2 = new Object();
	
    /** 取鸡蛋 */  
    public synchronized Object getEgg() {  
        while (eggs.size() == 0) {  
            try {  
            	wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        } 
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        Object egg = eggs.get(eggs.size()-1); 
        //eggs.remove(eggs.size()-1);
        eggs.clear();// 清空盘子  
        notify();// 唤醒阻塞队列的某线程到就绪队列 
        System.out.println("拿到鸡蛋");  
        return egg;  
    }  
    /** 放鸡蛋 */  
    public synchronized void putEgg(Object egg) {  
        while (eggs.size() > 0) {  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
        eggs.add(egg);// 往盘子里放鸡蛋  
        notify();// 唤醒阻塞队列的某线程到就绪队列  
        System.out.println("放入鸡蛋");  
    }  
    static class AddThread implements Runnable  {  
        private Plate2 plate;  
        private Object egg = new Object();  
        public AddThread(Plate2 plate) {  
            this.plate = plate;  
        }  
        public void run() {  
            plate.putEgg(egg);  
        }  
    }  
    static class GetThread implements Runnable  {  
        private Plate2 plate;  
        public GetThread(Plate2 plate) {  
            this.plate = plate;  
        }  
        public void run() {  
            plate.getEgg();  
        }  
    }  
    public static void main(String args[]) {  
        Plate2 plate = new Plate2();  
        for(int i = 0; i < 10; i++) {  
            new Thread(new AddThread(plate)).start();  
            new Thread(new GetThread(plate)).start();  
        }  
    }  
}  
